package service

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"io"
	"net/http"
	"net/url"
	"sync"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func Post[T any](requestUrl string, data []byte, c *gin.Context) (T, error) {
	body, err := PostFunction(requestUrl, data, nil)
	if err != nil {
		logrus.Error(err.Error())
		var errorMessage T
		return errorMessage, err
	}
	logrus.Debug("调用成功" + requestUrl)
	var Response T
	json.Unmarshal(body, &Response)
	return Response, nil
}

func Get[T any](requestUrl string, params map[string]string, c *gin.Context) (T, error) {
	u, _ := url.ParseRequestURI(requestUrl)
	data := url.Values{}
	if params != nil {
		for i, v := range params {
			data.Set(i, v)
		}
		u.RawQuery = data.Encode() // URL encode
	}
	body, err := GetFunction(u.String(), nil)
	if err != nil {
		logrus.Error(err.Error())
		var errorMessage T
		return errorMessage, err
	}
	logrus.Debug("调用成功" + requestUrl)
	var Response T
	json.Unmarshal(body, &Response)
	return Response, nil
}

func PostFunction(requestUrl string, data []byte, headers map[string]string) ([]byte, error) {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr, Timeout: 20 * time.Second}
	req, err := http.NewRequest("POST", requestUrl, bytes.NewBuffer(data))
	if err != nil {
		return nil, err
	}
	// 设置请求头，包括Content-Type为application/json
	req.Header.Set("Content-Type", "application/json")
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}

func GetFunction(requestUrl string, headers map[string]string) ([]byte, error) {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr, Timeout: 20 * time.Second}
	req, err := http.NewRequest("GET", requestUrl, nil)
	if err != nil {
		return nil, err
	}

	// 设置请求头
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return body, nil
}

func SuccessResponse[T any](data T) ResponseBody[T] {
	var responseValue ResponseBody[T]
	responseValue.Code = 200
	responseValue.Message = "success"
	responseValue.Data = data
	return responseValue
}

func ErrorResponse(code int, err error) ResponseBody[error] {
	var responseValue ResponseBody[error]
	responseValue.Code = code
	responseValue.Message = "fail"
	responseValue.Data = err
	return responseValue
}

type TokenRequest struct {
	Params TokenRequestBody `json:"params"`
}
type TokenRequestBody struct {
	Appkey     string `json:"appkey"`
	Appsecret  string `json:"appsecret"`
	Macaddress string `json:"macaddress"`
}

func CreateToken(wg *sync.WaitGroup, ch chan<- string) {
	var requestParams TokenRequest
	requestParams.Params.Appkey = "8f2f075f-8d9c-4294-b92f-c3b8f6b99908"
	requestParams.Params.Appsecret = "8ee9fd1b-feed-4b3d-ac21-42ea914ab6a9"
	requestParams.Params.Macaddress = "54:B2:03:9A:92:11"

	jsonData, errJson := json.Marshal((requestParams))
	if errJson != nil {
		logrus.Error(errJson)
		ch <- ""
	}
	requestUrl := baseUrl_stock + "XzspjYtjYdlbCreateToken"
	data := []byte(string(jsonData))
	body, err := PostFunction(requestUrl, data, nil)
	if err != nil {
		logrus.Error(errJson)
		ch <- ""
	}
	var Response ResponsePack[CreateTokenResponse]
	json.Unmarshal(body, &Response)
	ch <- Response.Custom.Token
	defer wg.Done()
}
